package com.qf.service.impl;

import com.qf.config.IdWorker;
import com.qf.constant.*;
import com.qf.feign.CacheService;
import com.qf.model.StandardSubmit;
import com.qf.service.SmsInterfaceService;
import com.qf.vo.SmsInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author lenovo
 * @version V1.0
 * @Date 2021/11/22 16:48
 */

@Service
@Slf4j
public class SmsInterfaceServiceImpl implements SmsInterfaceService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Map<String, String> checkSms(SmsInterface sms) {
        Map<String,String> resultMap = new HashMap<>();
        //1.调用Cache模块缓存接口，获取redis中的基础数据
        Map<String,String> client = cacheService.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + sms.getClientID());

        //2.检验客户端id是否正确
        if (client == null || client.size() == 0){
            log.info("【接口模块 - SmsInterfaceServiceImpl类】，客户端id错误，SmsInterface = {}",sms);
            resultMap.put("code", InterfaceExceptionDict.RETURN_STATUS_CLIENTID_ERROR);
            resultMap.put("msg","认证错：clientId错误");
            return resultMap;
        }
        //3.校验密码是否正确
        String redispwd = client.get("pwd");
        if (StringUtils.isEmpty(redispwd) || !redispwd.equals(sms.getPwd())){
            log.info("【接口模块 - SmsInterfaceServiceImpl类】，客户端密码错误，SmsInterface = {}",sms);
            resultMap.put("code", InterfaceExceptionDict.RETURN_STATUS_PWD_ERROR);
            resultMap.put("msg","认证错：密码错误");
            return resultMap;
        }

        //4.校验短信内容是否符合要求
        //5.校验目标手机号是否正确
        //用于存放非法的手机号
        Set<String> errorMobile = new HashSet<>();
        //校验手机号的正则
        String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        String mobiles = sms.getMobile();
        for (String mobile : mobiles.split(",")) {
            if (!mobile.matches(regex)){
                errorMobile.add(mobile);
            }
        }
        if (errorMobile.size() > 0){
            log.info("【接口模块 - SmsInterfaceServiceImpl类】，客户端密码错误，SmsInterface = {}",sms);
            resultMap.put("code", InterfaceExceptionDict.RETURN_STATUS_MOBILE_ERROR);
            resultMap.put("msg","认证错：手机号错误");
            return resultMap;
        }

        //6.校验下行编码,下行编码必须为长整型long
        try {
            long srcID = Long.parseLong(sms.getSrcID());
        } catch (NumberFormatException e) {
            log.info("【接口模块 - SmsInterfaceServiceImpl类】，客户端密码错误，SmsInterface = {}",sms);
            resultMap.put("code", InterfaceExceptionDict.RETURN_STATUS_SRCID_ERROR);
            resultMap.put("msg","认证错：下行编码错误");
            return resultMap;
        }

        //7.校验ip地址
        String ipaddress = client.get("ipaddress");
        if (StringUtils.isEmpty(ipaddress) || !ipaddress.equals(sms.getIp())){
            log.info("【接口模块 - SmsInterfaceServiceImpl类】，客户端密码错误，SmsInterface = {}",sms);
            resultMap.put("code", InterfaceExceptionDict.RETURN_STATUS_IP_ERROR);
            resultMap.put("msg","认证错：ip地址错误");
            return resultMap;
        }

        //封装内部需要使用的短信对象，发送到MQ中削锋
        for (String mobile : mobiles.split(",")) {
            StandardSubmit standardSubmit = new StandardSubmit();
            //当前StandardSubmit唯一id
            standardSubmit.setSequenceId(String.valueOf(idWorker.nextId()));
            //客户端id
            standardSubmit.setClientID(sms.getClientID());
            //消息的优先级 0最低 --- 3最高
            standardSubmit.setMessagePriority(Short.parseShort(client.get("priority")));
            //客户端唯一序列号
            standardSubmit.setSrcSequenceId(Long.parseLong(sms.getSrcID()));
            //目的手机号
            standardSubmit.setDestMobile(mobile);
            //短信内容
            standardSubmit.setMessageContent(sms.getContent());
            //手机接收的状态值 0成功 1等待 2失败
            standardSubmit.setReportState(ReportStateConstants.WAIT);
            //短信发送时间
            LocalDateTime localDateTime = LocalDateTime.now();
            Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
            Date date = Date.from(instant);
            standardSubmit.setSendTime(date);
            //发送方式 1http 2web
            standardSubmit.setSource(SourceType.HTTP);

            rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_PRE_SEND,standardSubmit);
        }


        resultMap.put("code","0");
        resultMap.put("msg","接收成功");
        return resultMap;
    }
}
